'use strict';

const express = require('express');
var multer = require("multer");
var request = require('request');
var co = require('co');
var qiniu = require("qiniu");
var fs = require('fs');
var path = require('path');
var WXPay = require('weixin-pay');
const Sequelize = require('sequelize');


const config = require('../config');
const Log = require("../model/log");
const User = require('../model/user');
const Message = require('../model/message');
const MessageImage = require('../model/messageImage');
const MessageLike = require('../model/messageLike');
const MessageComment = require('../model/messageComment');
const MessageReport = require('../model/messageReport');
const Notice = require('../model/notice');
const Donate = require('../model/donate');
const Util = require('../util/util');
const router = express.Router();

const LoginService = require('qcloud-weapp-server-sdk').LoginService;


var upload = multer({
    dest: 'uploads/'
})

var sequelize = new Sequelize('demo', 'cdb_outerroot', 'DDLNagijkQ3x', {
    host: '10.66.181.125',
    port: 3306,
    dialect: 'mysql',
    pool: {
        max: 10,
        min: 0,
        idle: 10000
    }
});




let qiniuAaccessKey = config.qiniuAccessKey;
let qiniuSecretKey = config.qiniuSecretKey;

let qiniuBucket = config.qiniuBucket;
let qiniuOutsideChain = config.qiniuOutsideChain;

qiniu.conf.ACCESS_KEY = qiniuAaccessKey;
qiniu.conf.SECRET_KEY = qiniuSecretKey;

const cert_file_path = path.join(__dirname, '/apiclient_cert.p12');
console.log("cert_file_path:" + cert_file_path);
const cert_file = fs.readFileSync(cert_file_path);
var wxpay = WXPay({
    appid: 'wxe50e25bcde08bcc3',
    mch_id: '1408994002',
    partner_key: 'DmuawyXOmCNd9XxW8d1gunPpq9QFvkAY', //微信商户平台API密钥
    pfx: cert_file, //微信商户平台证书
});


router.get('/', require('./welcome'));
router.get('/login', require('./login'));
router.get('/user', require('./user'));
router.all('/tunnel', require('./tunnel'));

router.get('/test', function(req, res) {
    console.log("test");
    res.send('OK');

});

// 首页的message list请求
router.get('/message/list', function(req, res) {
    // 分页查询
    var params = req.query;
    console.log("index param:" + JSON.stringify(params));
    var latitude = params.latitude;
    var longitude = params.longitude;
    var page = params.page || 1;
    var countPerPage = parseInt(params.perNumber) || 10;
    var currentPage = page;
    var userId = params.userId;

    var isSelf = params.isSelf;
    isSelf = parseInt(isSelf);

    var commentMessageIds = params.commentMessageIds;

    co(function*() {
        // code here
        var messages;

        if (isSelf) {
            // 显示自己

            if (!commentMessageIds) {
                messages = yield Message.findAll({
                    'limit': countPerPage, // 每页多少条
                    'offset': countPerPage * (currentPage - 1), // 跳过多少条
                    'order': "id DESC",
                    where: {
                        userId: userId,
                        state: {
                            '$ne': -1
                        }
                    }
                });
            } else {
                console.log("commentMessageIds:" + commentMessageIds + JSON.stringify(commentMessageIds));
                // messages = yield Message.findAll({
                //     'limit': countPerPage, // 每页多少条
                //     'offset': countPerPage * (currentPage - 1), // 跳过多少条
                //     'order': "id DESC",
                //     where: {
                //         id: {
                //             '$in': commentMessageIds
                //         },
                //         state: {
                //             '$ne': -1
                //         }
                //     }
                // });
                commentMessageIds = eval('(' + commentMessageIds + ')');
                var ids = "";
                for (let i = 0; i < commentMessageIds.length; i++) {
                    ids += commentMessageIds[i];
                    if (i != commentMessageIds.length - 1) {
                        ids += ",";
                    }
                }
                var offset = countPerPage * (currentPage - 1);
                let sql = "select m.* from messages m where m.id in (" + ids + ") and m.state!=-1 order by id desc ";
                var querySql = sql + "limit " + offset + "," + countPerPage;
                var messages = yield sequelize.query(querySql, { type: sequelize.QueryTypes.SELECT });

            }
        } else {
            // query sql
            var offset = countPerPage * (currentPage - 1);
            let sql = "select ms.* from ( select m.* , st_distance (point (m.`latitude`, m.`longitude`),point(" + latitude + ", " + longitude + ") ) * 111195 as distance from messages m) ms where ms.state!=-1 order by distance, id desc ";
            var querySql = sql + "limit " + offset + "," + countPerPage;
            var messages = yield sequelize.query(querySql, { type: sequelize.QueryTypes.SELECT });
            console.log("--messages:" + messages);
            // var messages = yield Message.findAll({
            //     'limit': countPerPage, // 每页多少条
            //     'offset': countPerPage * (currentPage - 1), // 跳过多少条
            //     'order': "id DESC",
            //     where: {
            //         state: {
            //             '$ne': -1
            //         }
            //     }
            // });
        }


        var result = [];
        for (let i = 0; i < messages.length; i++) {
            var message = messages[i];

            var indexObj = {};
            message.distance = Util.getGreatCircleDistance(latitude, longitude, message.latitude, message.longitude);
            console.log("distance:" + message.distance);
            indexObj.message = message;
            // 检查是否有图片
            var images = yield MessageImage.findAll({
                where: {
                    messageId: message.id
                }
            });
            indexObj.images = images;

            // enable do like
            indexObj.enableLike = 1;
            if (message.likes > 0) {
                var messageLikeCount = yield MessageLike.count({
                    where: {
                        userId: userId,
                        messageId: message.id
                    }
                });
                if (messageLikeCount > 0) {
                    indexObj.enableLike = 0;
                }
            }


            result.push(indexObj);
        }

        return res.json({
            success: true,
            result: result
        });
    }).catch(function(e) {
        console.log(e);
    });


});

// 发布message
router.post('/message/add', function(req, res) {
    var params = req.body;
    var files = new Array(params.uploadedFiles.length);
    for (let i = 0; i < params.uploadedFiles.length; i++) {
        var fileObj = params.uploadedFiles[i];
        files[fileObj.index] = fileObj.qiniuUrl;
    }
    console.log("files:" + files);
    const loginService = LoginService.create(req, res);
    loginService.check().then(function(data) {
        //验证OK
        console.log("userInfo:" + JSON.stringify(data.userInfo));
        var userInfo = data.userInfo;
        var openId = userInfo.openId;
        console.log("openId:" + openId);
        User.findOne({
            where: {
                openId: openId
            }
        }).then(function(user) {
            // 拿到用户的数据构建message对象
            var message = {};
            console.log("user:" + user);
            console.log("string:" + JSON.stringify(user));
            console.log("userid:" + user.id);
            console.log("nickName:" + user.nickName);
            message.userId = user.id;
            message.userName = user.nickName;
            message.userGender = user.gender;
            message.city = user.city;
            message.province = user.province;
            message.avatarUrl = user.avatarUrl;
            message.content = params.content;
            message.latitude = params.latitude;
            message.longitude = params.longitude;
            message.locationTitle = params.locationTitle;
            Message.create(message).then(function(message) {
                // add upload files
                console.log("result new message:" + message);
                Promise.all([files.map(i => {
                    return new Promise((resolve, reject) => {
                        resolve(MessageImage.create({
                            messageId: message.id,
                            url: i
                        }))
                    })
                })]).then(result => {
                    //获得十笔查询后的记录
                    console.log(result);
                    res.json({
                        success: true
                    });
                })
            });

        })

        // console.log(req.body);

        // res.json(req.body);

    }).catch(function(reason) {
        console.log("message add error");
        res.json({
            success: false
        });
    });
    // 拿到提交的数据，插入数据库
    // 消息内容，提交的用户，位置，文件列表的对象

});


// 首页的message list请求
router.get('/message/detail', function(req, res) {
    // 分页查询
    var params = req.query;
    // console.log("detail param:" + JSON.stringify(params));
    var messageId = parseInt(params.messageId);
    var latitude = params.latitude;
    var longitude = params.longitude;
    var userId = params.userId;

    co(function*() {
        // code here
        var message = yield Message.findOne({
            where: {
                id: messageId
            }
        });
        message.read = message.read + 1;
        // 打开的次数
        var changed = yield Message.update({
            read: message.read
        }, {
            where: {
                id: messageId
            }
        });

        var indexObj = {};
        message.distance = Util.getGreatCircleDistance(latitude, longitude, message.latitude, message.longitude);
        console.log("distance:" + message.distance);
        indexObj.message = message;
        // 检查是否有图片
        var images = yield MessageImage.findAll({
            where: {
                messageId: messageId
            }
        });
        indexObj.images = images;

        // enable do like
        indexObj.enableLike = 1;
        if (message.likes > 0) {
            var messageLikeCount = yield MessageLike.count({
                where: {
                    userId: userId,
                    messageId: messageId
                }
            });
            console.log('messageLikeCount:' + messageLikeCount);
            if (messageLikeCount > 0) {
                indexObj.enableLike = 0;
            }
        }

        // 查找评论
        var comments = yield MessageComment.findAll({
            where: {
                messageId: messageId
            }
        });

        indexObj.comments = comments;


        return res.json({
            success: true,
            result: indexObj
        });
    }).catch(function(e) {
        console.log(e);
    });
});


router.post('/message/comment', function(req, res) {
    // 用户回复评论
    co(function*() {
        var params = req.body;
        console.log("comment:" + JSON.stringify(params));
        // 消息id, 当前用户id, 昵称, 头像, 回复内容
        var messageId = params.messageId;
        var userId = params.userId;
        var userName = params.userName;
        var avatarUrl = params.avatarUrl;
        var comment = params.comment;
        var replyCommentId = params.replyCommentId;
        var userGender = params.gender;
        var messageComment = {
            messageId: messageId,
            userId: userId,
            userName: userName,
            avatarUrl: avatarUrl,
            comment: comment,
            replyCommentId: replyCommentId,
            userGender: userGender
        };

        var messageComment = yield MessageComment.create(messageComment);

        var comments = yield MessageComment.findAll({
            where: {
                messageId: messageId
            }
        });

        var message = yield Message.update({
            comment: comments.length
        }, {
            where: {
                id: messageId
            }
        });

        return res.json({
            success: true,
            result: comments
        });
    });
})

/**
 * 举报
 */
router.post('/message/report', function(req, res) {
    co(function*() {
        var params = req.body;
        console.log("report:" + JSON.stringify(params));

        var report = {
            messageId: params.messageId,
            userId: params.userId
        }

        report = MessageReport.create(report);
        return res.json({
            success: true,
            result: report
        });

    });
});

// 捐赠 要生成捐赠单据
router.post('/donate', function(req, res) {
    // 捐赠给的用户ID
    // 捐赠的金额
    var params = req.body;
    console.log("donate:" + JSON.stringify(params));
    // {"fromUserOpenId":"o3Xv50C_CTf2yj7t4X8PO4oGxr38","toUserId":"1","donateAmount":1}
    var openId = params.fromUserOpenId;
    var toUserId = params.toUserId;
    var amount = params.donateAmount;
    co(function*() {
        // find user id
        var _user = yield User.findOne({
            where: {
                openId: openId
            }
        });
        var userId = _user.id;

        var donate = {};
        donate.userId = userId;
        donate.toUserId = toUserId;
        donate.amount = amount;
        donate.state = 0;
        donate = yield Donate.create(donate);

        return res.json({
            success: true,
            result: donate
        });


    }).catch(function(e) {
        console.log(e);
    });


    // wxpay.getBrandWCPayRequestParams({
    //     openid: '微信用户 openid',
    //     body: '公众号支付测试',
    //     detail: '公众号支付测试',
    //     out_trade_no: '20150331'+Math.random().toString().substr(2, 10),
    //     total_fee: 1,
    //     spbill_create_ip: '192.168.2.210',
    //     notify_url: 'http://wxpay_notify_url'
    // }, function(err, result){
    //     // in express
    //     res.render('wxpay/jsapi', { payargs:result })
    // });

    // res.json({
    //     success: true
    // });

});


// 捐赠 要生成捐赠单据
router.post('/dolike', function(req, res) {
    // messageId
    // openId
    var params = req.body;
    console.log("donate:" + JSON.stringify(params));
    // {"fromUserOpenId":"o3Xv50C_CTf2yj7t4X8PO4oGxr38","toUserId":"1","donateAmount":1}
    var userId = params.userId;
    var messageId = params.messageId;
    var like = params.like;
    co(function*() {
        let messageLike = yield MessageLike.findOne({
            where: {
                userId: userId,
                messageId: messageId
            }
        });
        console.log("messageLike:" + messageLike);
        if (like == 1) {
            // 点赞
            if (!messageLike) {
                let messageLike = yield MessageLike.create({
                    messageId: messageId,
                    userId: userId
                });
            }
        } else {
            // 取消点赞
            if (messageLike) {
                let result = yield MessageLike.destroy({
                    where: {
                        id: messageLike.id
                    }
                });
            }
        }

        let likeCount = yield MessageLike.count({
            where: {
                messageId: messageId
            }
        });
        var message = yield Message.update({
            likes: likeCount
        }, {
            where: {
                id: messageId
            }
        });

        return res.json({
            success: true,
            result: {
                messageId: messageId,
                likeCount: likeCount
            }
        });


    }).catch(function(e) {
        console.log(e);
    });

});


// 上传文件
router.post("/file/upload", upload.single('wxFile'), function(req, res) {
    // console.log(req.file);
    var file = req.file;

    var filePath = file.path;
    let fileType = file.originalname.split(".").pop();
    console.log("file:" + filePath + "." + fileType);

    if (filePath) {
        var key = file.filename + "." + fileType;
        console.log("key:" + key);
        console.log("qiniuBucket:" + qiniuBucket);
        var putPolicy = new qiniu.rs.PutPolicy(qiniuBucket + ":" + key);
        var token = putPolicy.token();
        console.log("token:" + token);
        var extra = new qiniu.io.PutExtra();
        qiniu.io.putFile(token, key, filePath, extra, function(err, ret) {
            if (!err) {
                // 上传成功， 处理返回值 并删除数据
                fs.unlink(filePath);
                // resolve(ret);
                console.log("upload file success");
                var qiniuFilePath = qiniuOutsideChain + ret.key;
                console.log("qiniuFilePath:" + qiniuFilePath);
                res.json({
                    qiniuUrl: qiniuFilePath
                });
            } else {
                // 上传失败， 处理返回代码
                console.log(err);
                res.json({
                    success: false
                });
            }
        });
    }

});

let keys = config.qqMapKeys;
var _keyIndex = 0;
// 获取当前位置的名称的 address title list /address/list
router.all("/address/list", function(req, res) {
    console.log('query:' + JSON.stringify(req.query));
    console.log('body:' + JSON.stringify(req.query));
    let latitude = req.query.latitude;
    let longitude = req.query.longitude;

    if (_keyIndex >= keys.length) {
        _keyIndex = 0;
    }

    var _key = keys[_keyIndex++];
    var requestUrl = "http://apis.map.qq.com/ws/place/v1/search?key=" + _key + "&boundary=nearby(" + latitude + "," + longitude + ",2000)&page_size=10&page_index=1&orderby=_distance";
    console.log(requestUrl);
    request(requestUrl, function(error, response, result) {
        if (!error && response.statusCode == 200) {
            result = JSON.parse(result);
            res.json(result.data);
        }
    });
});

router.get("/self", function(req, res) {
    console.log('query:' + JSON.stringify(req.query));
    console.log('body:' + JSON.stringify(req.body));
    var userId = req.query.userid;
    // 获取用户的数据
    co(function*() {
        var user = yield User.findOne({
            where: {
                id: userId
            }
        });

        var result = {};
        result.user = user;

        // 我的动态
        var myMessageCount = yield Message.count({
            where: {
                userId: userId
            }
        });
        result.myMessageCount = myMessageCount;

        // 我的回复的动态

        var myComments = yield MessageComment.findAll({
            where: {
                userId: userId
            }
        });
        var myCommentMessageIds = [];
        for (let i = 0; i < myComments.length; i++) {
            var comment = myComments[i];
            var messageid = parseInt(comment.messageId)
            if (myCommentMessageIds.indexOf(messageid) < 0) {
                myCommentMessageIds.push(messageid);
            }
        }
        result.commentMessageIds = myCommentMessageIds;

        // 系统通知
        var notices = yield Notice.findAll({
            'order': "id DESC",
            where: {
                toUserId: userId
            }
        });
        result.notices = notices;

        res.json({
            success: false,
            result: result
        });
    });
});

// 查看详细的message

module.exports = router;